<template>
    <div class="company-info" @click="handleClick(companyInfo.id)">
        <!-- 动态绑定样式 -->
        <div class="company-logo" :style="{ backgroundColor: randomBgColor }">
          <span>
            {{(companyInfo.alias && companyInfo.alias.length > 2)
            ? companyInfo.alias.slice(0, 2) + '\n' + companyInfo.alias.slice(2)
            : (companyInfo.alias || '--')}}
          </span>
        </div>
        <div class="company-details">
            <div class="info-item" style="overflow: hidden;">
                <span class="name" style="float: left;" v-html="highlightedName"></span>
                <span class="status" style="float: left;margin-top: 5px;">{{ companyInfo.regStatus || '--' }}</span>
            </div>
            <div class="deta_bot" v-if="companyInfo.lockFlag == 0">
                <div class="info-item">
                    <span class="label">法定代表人：</span>
                    <span class="value">{{ companyInfo.legalPersonName || '--' }}</span>
                </div>
                <div class="info-item">
                    <span class="label">注册资本：</span>
                    <span class="value">{{ companyInfo.regCapital || '--' }}</span>
                </div>
                <div class="info-item">
                    <span class="label">成立日期：</span>
                    <span class="value">{{ formatTimestamp(companyInfo.estiblishTime) || '--' }}</span>
                </div>
                <div class="info-item">
                    <span class="label">统一社会信用代码：</span>
                    <el-tooltip
      :content="companyInfo.creditCode || '--'"
      placement="top"
    >
                    <span class="value">{{ companyInfo.creditCode || '--' }}</span>
                </el-tooltip>
                </div>
                <div class="info-item">
                    <span class="label">联系人信息：</span>
                    <span class="value">{{ companyInfo.userName || '--' }}</span>
                  &nbsp;
                    <span class="value">{{ companyInfo.position || '' }}</span>
                </div>
                <div class="info-item">
                    <span class="label">地址：</span>
                    <el-tooltip
      :content="companyInfo.regLocation || '--'"
      placement="top"
                    >
                    <span class="value">{{ companyInfo.regLocation || '--' }}</span>
                    </el-tooltip>
                </div>
            </div>
            <!-- 添加点击事件 -->
            <div v-else class="suo" @click.stop="handleSuoClick">
                <el-image :src="logoImage" />
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from "element-plus";
import baseService from "@/service/baseService";
const router = useRouter();

// 定义组件接收的 props
const props = defineProps<{
    companyInfo: {
        keywords: string;
        name: string;
        id: string;
        legalPersonName: string;
        regCapital: string;
        estiblishTime: string;
        creditCode: string;
        contactInfo: string;
        regLocation: string;
        Unlock: number;
        regStatus: string;
        lockFlag: number;
    };
    searchKeyword: string; // 新增：搜索关键词
}>();

import logoImage from '@/assets/images/jiesuo.png';

// 添加 isUnlocking 状态变量，用于防止重复点击
const isUnlocking = ref(false);

// 定义随机背景颜色和字体颜色的 ref
const randomBgColor = ref('');
const randomTextColor = ref('');

// 定义要触发的事件
const emit = defineEmits(['child-action']);

// 定义固定颜色数组
const fixedColors = [
    '#13D7C6', '#0594FF', '#5733FF', '#FFC300', '#33A6FF', '#FFD733'
];

// 生成随机颜色的函数，从固定颜色中随机选取
const getRandomColor = () => {
    const randomIndex = Math.floor(Math.random() * fixedColors.length);
    return fixedColors[randomIndex];
};

// 时间戳转换为 YYYY-MM-DD 格式日期的方法，增加空值判断
const formatTimestamp = (timestamp: number | string | null | undefined): string => {
    if (!timestamp) {
        return '暂无数据';
    }
    const date = new Date(Number(timestamp));
    if (isNaN(date.getTime())) {
        return '暂无数据';
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

const handleClick = (id: string) => {
    if (props.companyInfo.lockFlag == 0) {
        router.push({
            path: '/company-detail',
            query: {
                id: id,
                name: props.searchKeyword
            }
        })
    }

    console.log(id);
};

// 修改 handleSuoClick 方法，添加防重复点击逻辑
const handleSuoClick = () => {
    // 如果正在解锁，则提示用户不要重复操作
    if (isUnlocking.value) {
        ElMessage({
            message: '请勿重复操作',
            type: 'warning',
        });
        return;
    }

    // 设置正在解锁状态
    isUnlocking.value = true;

    baseService.post('/noc/vip/unlock', { companyId: parseInt(props.companyInfo.id) }).then((res) => {
        if (res.code == 0 && res.data.success == true) {
            ElMessage({
                message: '解锁成功',
                type: 'success',
            });

            if (res.data) {
                props.companyInfo.lockFlag = 0;
                props.companyInfo.name = res.data.CompanyName;
                props.companyInfo.regCapital = res.data.regCapital;
                props.companyInfo.estiblishTime = res.data.estiblishTime;
                props.companyInfo.creditCode = res.data.creditCode;
                props.companyInfo.regLocation = res.data.regLocation;
            }
        } else {
            emit('child-action', { id: 1 });
        }
    }).finally(() => {
        // 无论成功或失败，都重置 isUnlocking 状态
        isUnlocking.value = false;
    });
};

// 新增：处理名称高亮逻辑
const highlightedName = computed(() => {
    const name = props.companyInfo.name || '暂无数据';
    const keyword = props.searchKeyword;

    // 关键词为空时直接返回原名称
    if (!keyword) return name;

    // 正则匹配关键词（忽略大小写），用<span>包裹匹配部分
    const regex = new RegExp(`(${escapeRegExp(keyword)})`, 'gi');
    return name.replace(regex, '<span class="highlight">$1</span>');
});

// 辅助函数：转义正则特殊字符
const escapeRegExp = (str: string) => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

onMounted(() => {
    // 组件挂载时生成随机颜色
    randomBgColor.value = getRandomColor();
    randomTextColor.value = getRandomColor();
});
</script>

<style scoped lang="less">
.company-info {
    display: flex;
    gap: 20px;
    font-family: "Microsoft YaHei";
    padding: 36px 0;
    border-bottom: 1px solid rgba(199, 199, 199, 1);
}

.company-logo {
    width: 83px;
    height: 83px;
    line-height: 83px;
    border-radius: 15px;
    display: flex;
    color: #fff;
    font-size: 20px;
    justify-content: center;
    align-items: center;
}
.company-logo span {
  white-space: pre-line;
  line-height: 25px;
}
.suo{
    text-align: center;
    padding-top: 29px;
    cursor: pointer
}

.company-details {
    flex: 1;
    padding-left: 41px;
}

.info-item {
    margin-bottom: 10px;
}

.label {
    margin-right: 10px;
}

.name {
    color: rgba(0, 0, 0, 1);
    font-size: 24px;
}

/* 新增：高亮样式 */

::v-deep .name .highlight {
    color: rgba(212, 48, 48, 1);
    /* 高亮 */
    padding: 0 2px;
}

.status {
    border-radius: 5px;
    background: #eff4ff;
    color: rgba(16, 98, 202, 1);
    line-height: 23px;
    margin-left: 21px;
    font-size: 16px;
    width: 61px;
    text-align: center;
    display: inline-block;
    border: 1px solid rgba(16, 98, 202, 1);
}

.value {
    color: #333;
}

/* 修改 .deta_bot 样式 */
.deta_bot {
    display: flex;
    flex-wrap: wrap;
    gap: 6;
    /* 设置间隔为 15 像素 */
}

/* 修改 .deta_bot 内的 .info-item 样式 */
.deta_bot .info-item {
    width: 343px;
    /* 设置宽度为 323 像素 */
    overflow: hidden;
    text-overflow: ellipsis;
    font-size: 16px;
    color:rgba(56, 56, 56, 1);
    white-space: nowrap;
}

/* 让 .value 也支持超出省略 */
.deta_bot .info-item .value {
    max-width: calc(100% - 100px);
    /* 减去 label 的大致宽度 */
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: top;
}
</style>
